package com.benefm.multipar.pad.view;

import android.view.View;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.View;

import com.benefm.multipar.pad.R;

import java.util.Random;

public class BloodPressureGauge extends View {
    // 血压指标范围
    private static final int SYS_MIN = 60;   // 收缩压最小值
    private static final int SYS_MAX = 200;  // 收缩压最大值
    private static final int DIA_MIN = 40;   // 舒张压最小值
    private static final int DIA_MAX = 120;  // 舒张压最大值

    // 血压状态阈值（mmHg）
    private static final int SYS_HYPERTENSION = 140; // 收缩压高血压阈值
    private static final int DIA_HYPERTENSION = 90;  // 舒张压高血压阈值
    private static final int SYS_HYPOTENSION = 90;   // 收缩压低血压阈值
    private static final int DIA_HYPOTENSION = 60;   // 舒张压低血压阈值

    // 外环（收缩压）参数
    private Paint outerRingPaint, outerValuePaint;
    private int systolicValue = 120; // 收缩压
    private int systolicAngle = 0;   // 收缩压角度

    // 内环（舒张压）参数
    private Paint innerRingPaint, innerValuePaint;
    private int diastolicValue = 80; // 舒张压
    private int diastolicAngle = 0;  // 舒张压角度

    // 中心显示
    private Paint centerValuePaint, centerLabelPaint;

    // 血压状态标识
    private Paint statusPaint;
    private String pressureStatus = "NORMAL";
    private int statusColor = Color.GREEN;

    // 环形区域
    private RectF outerRingRect, innerRingRect;
    private int width, height;
    private float centerX, centerY;
    private float radius;

    // 动画和交互
    private ValueAnimator systolicAnimator, diastolicAnimator;
    private Random random = new Random();

    // 颜色定义
    private final int BACKGROUND_COLOR = Color.parseColor("#263238");
    private final int NORMAL_COLOR = Color.parseColor("#4CAF50");
    private final int HYPERTENSION_COLOR = Color.parseColor("#F44336");
    private final int HYPOTENSION_COLOR = Color.parseColor("#2196F3");
    private final int OUTER_RING_COLOR = Color.parseColor("#37474F");
    private final int INNER_RING_COLOR = Color.parseColor("#2C3E50");
    private final int TEXT_COLOR = Color.parseColor("#ECEFF1");
    private final int GRID_COLOR = Color.parseColor("#546E7A");

    public BloodPressureGauge(Context context) {
        super(context);
        init(null);
    }

    public BloodPressureGauge(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        // 解析自定义属性
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.BloodPressureGauge);
            systolicValue = a.getInt(R.styleable.BloodPressureGauge_systolic, systolicValue);
            diastolicValue = a.getInt(R.styleable.BloodPressureGauge_diastolic, diastolicValue);
            a.recycle();

            // 计算初始角度
            systolicAngle = calculateAngle(systolicValue, SYS_MIN, SYS_MAX);
            diastolicAngle = calculateAngle(diastolicValue, DIA_MIN, DIA_MAX);
        }

        // 更新血压状态
        updatePressureStatus();

        // 外环画笔（收缩压）
        outerRingPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        outerRingPaint.setStyle(Paint.Style.STROKE);
        outerRingPaint.setStrokeWidth(24f);
        outerRingPaint.setStrokeCap(Paint.Cap.ROUND);

        // 外环值显示画笔
        outerValuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        outerValuePaint.setTextSize(34f);
        outerValuePaint.setColor(TEXT_COLOR);
        outerValuePaint.setTypeface(Typeface.create(Typeface.DEFAULT,Typeface.BOLD));
        outerValuePaint.setTextAlign(Paint.Align.CENTER);

        // 内环画笔（舒张压）
        innerRingPaint = new Paint(outerRingPaint);
        innerRingPaint.setStrokeWidth(18f);

        // 内环值显示画笔
        innerValuePaint = new Paint(outerValuePaint);
        innerValuePaint.setTextSize(28f);

        // 中心值显示画笔
        centerValuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        centerValuePaint.setTextSize(56f);
        centerValuePaint.setColor(TEXT_COLOR);
        centerValuePaint.setTypeface(Typeface.create(Typeface.DEFAULT,Typeface.BOLD));
        centerValuePaint.setTextAlign(Paint.Align.CENTER);

        // 中心标签画笔
        centerLabelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        centerLabelPaint.setTextSize(22f);
        centerLabelPaint.setColor(TEXT_COLOR);
        centerLabelPaint.setTextAlign(Paint.Align.CENTER);

        // 状态标识画笔
        statusPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        statusPaint.setTextSize(26f);
        statusPaint.setColor(statusColor);
        statusPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
        statusPaint.setTextAlign(Paint.Align.CENTER);

        // 初始化环形区域
        outerRingRect = new RectF();
        innerRingRect = new RectF();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;

        radius = Math.min(width, height) * 0.38f;
        centerX = width / 2f;
        centerY = height / 2f;

        // 外环区域
        float outerRadius = radius * 1.0f;
        outerRingRect.set(
                centerX - outerRadius,
                centerY - outerRadius,
                centerX + outerRadius,
                centerY + outerRadius
        );

        // 内环区域
        float innerRadius = radius * 0.7f;
        innerRingRect.set(
                centerX - innerRadius,
                centerY - innerRadius,
                centerX + innerRadius,
                centerY + innerRadius
        );
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 1. 绘制背景
        drawBackground(canvas);

        // 2. 绘制外环（收缩压）
        drawSystolicRing(canvas);

        // 3. 绘制内环（舒张压）
        drawDiastolicRing(canvas);

        // 4. 绘制刻度值
//        drawScaleValues(canvas);

        // 5. 绘制中心区域
//        drawCenterDisplay(canvas);
    }

    private void drawBackground(Canvas canvas) {
        // 绘制背景圆
        Paint bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bgPaint.setColor(BACKGROUND_COLOR);
        bgPaint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(centerX, centerY, radius * 1.05f, bgPaint);

        // 绘制网格线（科技感）
        Paint gridPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        gridPaint.setStrokeWidth(1f);
        gridPaint.setColor(GRID_COLOR);
        gridPaint.setStyle(Paint.Style.STROKE);

        // 同心圆
        float[] radii = {radius * 0.2f, radius * 0.5f, radius * 0.8f};
        for (float r : radii) {
            canvas.drawCircle(centerX, centerY, r, gridPaint);
        }

        // 辐射线
        for (int i = 0; i < 12; i++) {
            float angle = i * 30;
            float rad = (float) Math.toRadians(angle);
            float x = centerX + radius * (float) Math.cos(rad);
            float y = centerY + radius * (float) Math.sin(rad);
            canvas.drawLine(centerX, centerY, x, y, gridPaint);
        }
    }

    private void drawSystolicRing(Canvas canvas) {
        // 背景环
        outerRingPaint.setColor(OUTER_RING_COLOR);
        canvas.drawArc(outerRingRect, 0, 360, false, outerRingPaint);

        // 绘制不同状态区域
        int normalStartAngle = calculateAngle(SYS_HYPOTENSION, SYS_MIN, SYS_MAX);
        int normalSweepAngle = calculateAngle(SYS_HYPERTENSION, SYS_MIN, SYS_MAX) - normalStartAngle;

        // 低血压区域
        outerRingPaint.setColor(HYPOTENSION_COLOR);
        canvas.drawArc(outerRingRect, 0, normalStartAngle, false, outerRingPaint);

        // 正常区域
        outerRingPaint.setColor(NORMAL_COLOR);
        canvas.drawArc(outerRingRect, normalStartAngle, normalSweepAngle, false, outerRingPaint);

        // 高血压区域
        outerRingPaint.setColor(HYPERTENSION_COLOR);
        canvas.drawArc(outerRingRect, normalStartAngle + normalSweepAngle, 360 - (normalStartAngle + normalSweepAngle), false, outerRingPaint);

        // 绘制当前值位置指示器
        int indicatorAngle = calculateAngle(systolicValue, SYS_MIN, SYS_MAX);
        float rad = (float) Math.toRadians(indicatorAngle);
        float startX = centerX;
        float startY = centerY;
        float endX = centerX + (radius - 10) * (float) Math.cos(rad);
        float endY = centerY + (radius - 10) * (float) Math.sin(rad);

        Paint indicatorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        indicatorPaint.setColor(Color.WHITE);
        indicatorPaint.setStrokeWidth(6f);
        canvas.drawLine(startX, startY, endX, endY, indicatorPaint);

        // 外端点标记
        Paint markerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        markerPaint.setStyle(Paint.Style.FILL);
        markerPaint.setColor(getColorForSystolic(systolicValue));
        canvas.drawCircle(endX, endY, 12, markerPaint);

        // 外环值显示
        String valueText = systolicValue + " mmHg";
        float valueX = centerX;
        float valueY = centerY - radius * 0.3f;
        canvas.drawText("收缩压", valueX, valueY - 30, centerLabelPaint);
        canvas.drawText(valueText, valueX, valueY, outerValuePaint);
    }

    private void drawDiastolicRing(Canvas canvas) {
        // 背景环
        innerRingPaint.setColor(INNER_RING_COLOR);
        canvas.drawArc(innerRingRect, 0, 360, false, innerRingPaint);

        // 绘制不同状态区域
        int normalStartAngle = calculateAngle(DIA_HYPOTENSION, DIA_MIN, DIA_MAX);
        int normalSweepAngle = calculateAngle(DIA_HYPERTENSION, DIA_MIN, DIA_MAX) - normalStartAngle;

        // 低血压区域
        innerRingPaint.setColor(HYPOTENSION_COLOR);
        canvas.drawArc(innerRingRect, 0, normalStartAngle, false, innerRingPaint);

        // 正常区域
        innerRingPaint.setColor(NORMAL_COLOR);
        canvas.drawArc(innerRingRect, normalStartAngle, normalSweepAngle, false, innerRingPaint);

        // 高血压区域
        innerRingPaint.setColor(HYPERTENSION_COLOR);
        canvas.drawArc(innerRingRect, normalStartAngle + normalSweepAngle, 360 - (normalStartAngle + normalSweepAngle), false, innerRingPaint);

        // 绘制当前值位置指示器
        int indicatorAngle = calculateAngle(diastolicValue, DIA_MIN, DIA_MAX);
        float rad = (float) Math.toRadians(indicatorAngle);
        float startX = centerX;
        float startY = centerY;
        float endX = centerX + (radius * 0.7f - 10) * (float) Math.cos(rad);
        float endY = centerY + (radius * 0.7f - 10) * (float) Math.sin(rad);

        Paint indicatorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        indicatorPaint.setColor(Color.WHITE);
        indicatorPaint.setStrokeWidth(5f);
        canvas.drawLine(startX, startY, endX, endY, indicatorPaint);

        // 内端点标记
        Paint markerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        markerPaint.setStyle(Paint.Style.FILL);
        markerPaint.setColor(getColorForDiastolic(diastolicValue));
        canvas.drawCircle(endX, endY, 10, markerPaint);

        // 内环值显示
        String valueText = diastolicValue + " mmHg";
        float valueX = centerX;
        float valueY = centerY + radius * 0.3f;
        canvas.drawText("舒张压", valueX, valueY - 30, centerLabelPaint);
        canvas.drawText(valueText, valueX, valueY, innerValuePaint);
    }

    private void drawScaleValues(Canvas canvas) {
        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextSize(18f);
        textPaint.setColor(Color.parseColor("#B0BEC5"));
        textPaint.setTextAlign(Paint.Align.CENTER);

        // 外环刻度值
        int[] sysValues = {60, 80, 100, 120, 140, 160, 180, 200};
        for (int value : sysValues) {
            int angle = calculateAngle(value, SYS_MIN, SYS_MAX);
            float rad = (float) Math.toRadians(angle);
            float radiusPos = radius * 1.15f;
            float x = centerX + radiusPos * (float) Math.cos(rad);
            float y = centerY + radiusPos * (float) Math.sin(rad) + 8;

            if (value == SYS_HYPERTENSION || value == SYS_HYPOTENSION) {
                Paint highlightPaint = new Paint(textPaint);
                highlightPaint.setColor(getColorForSystolic(value));
                highlightPaint.setTextSize(20f);
                highlightPaint.setTypeface(Typeface.DEFAULT_BOLD);
                canvas.drawText(String.valueOf(value), x, y, highlightPaint);
            } else {
                canvas.drawText(String.valueOf(value), x, y, textPaint);
            }
        }

        // 内环刻度值
        int[] diaValues = {40, 50, 60, 70, 80, 90, 100, 110, 120};
        for (int value : diaValues) {
            int angle = calculateAngle(value, DIA_MIN, DIA_MAX);
            float rad = (float) Math.toRadians(angle);
            float radiusPos = radius * 0.5f;
            float x = centerX + radiusPos * (float) Math.cos(rad);
            float y = centerY + radiusPos * (float) Math.sin(rad) + 8;

            if (value == DIA_HYPERTENSION || value == DIA_HYPOTENSION) {
                Paint highlightPaint = new Paint(textPaint);
                highlightPaint.setColor(getColorForDiastolic(value));
                highlightPaint.setTextSize(18f);
                highlightPaint.setTypeface(Typeface.DEFAULT_BOLD);
                canvas.drawText(String.valueOf(value), x, y, highlightPaint);
            } else {
                canvas.drawText(String.valueOf(value), x, y, textPaint);
            }
        }

        // 绘制分割线
        Paint separatorPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        separatorPaint.setColor(Color.WHITE);
        separatorPaint.setStrokeWidth(2f);

        float x1 = centerX - radius * 0.35f;
        float y1 = centerY - radius * 0.35f;
        float x2 = centerX + radius * 0.35f;
        float y2 = centerY + radius * 0.35f;

        canvas.drawLine(x1, y1, x2, y2, separatorPaint);
    }

    private void drawCenterDisplay(Canvas canvas) {
        // 绘制血压值
        String bpValue = systolicValue + " / " + diastolicValue;
        canvas.drawText(bpValue, centerX, centerY - 20, centerValuePaint);

        // 绘制单位
        canvas.drawText("血压 (mmHg)", centerX, centerY + 20, centerLabelPaint);

        // 绘制状态指示
        statusPaint.setColor(statusColor);
        canvas.drawText(pressureStatus, centerX, centerY + 60, statusPaint);

        // 绘制小标签
        Paint tagPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        tagPaint.setColor(statusColor);
        tagPaint.setStyle(Paint.Style.FILL);
        tagPaint.setAlpha(30);

        Path path = new Path();
        float tagRadius = radius * 0.25f;
        float tagAngle = 20;

        // 上标签
        path.reset();
        path.moveTo(centerX, centerY - tagRadius);
        path.lineTo(centerX - tagAngle, centerY - tagRadius - tagAngle);
        path.lineTo(centerX + tagAngle, centerY - tagRadius - tagAngle);
        path.close();
        canvas.drawPath(path, tagPaint);

        // 下标签
        path.reset();
        path.moveTo(centerX, centerY + tagRadius);
        path.lineTo(centerX - tagAngle, centerY + tagRadius + tagAngle);
        path.lineTo(centerX + tagAngle, centerY + tagRadius + tagAngle);
        path.close();
        canvas.drawPath(path, tagPaint);
    }

    // 计算血压值对应的角度
    private int calculateAngle(int value, int min, int max) {
        return (int) ((float)(value - min) / (max - min) * 360);
    }

    // 更新血压状态
    private void updatePressureStatus() {
        if (systolicValue >= SYS_HYPERTENSION || diastolicValue >= DIA_HYPERTENSION) {
            pressureStatus = "高血压";
            statusColor = HYPERTENSION_COLOR;
        } else if (systolicValue <= SYS_HYPOTENSION || diastolicValue <= DIA_HYPOTENSION) {
            pressureStatus = "低血压";
            statusColor = HYPOTENSION_COLOR;
        } else {
            pressureStatus = "正常";
            statusColor = NORMAL_COLOR;
        }
    }

    // 根据收缩压值获取颜色
    private int getColorForSystolic(int value) {
        if (value <= SYS_HYPOTENSION) {
            return HYPOTENSION_COLOR;
        } else if (value >= SYS_HYPERTENSION) {
            return HYPERTENSION_COLOR;
        } else {
            return NORMAL_COLOR;
        }
    }

    // 根据舒张压值获取颜色
    private int getColorForDiastolic(int value) {
        if (value <= DIA_HYPOTENSION) {
            return HYPOTENSION_COLOR;
        } else if (value >= DIA_HYPERTENSION) {
            return HYPERTENSION_COLOR;
        } else {
            return NORMAL_COLOR;
        }
    }

    // 设置收缩压（带动画）
    public void setSystolicValue(int value, boolean animate) {
        if (value < SYS_MIN) value = SYS_MIN;
        if (value > SYS_MAX) value = SYS_MAX;

        if (systolicAnimator != null && systolicAnimator.isRunning()) {
            systolicAnimator.cancel();
        }

        if (animate) {
            systolicAnimator = ValueAnimator.ofInt(systolicValue, value);
            systolicAnimator.setDuration(1500);
            systolicAnimator.addUpdateListener(animation -> {
                systolicValue = (int) animation.getAnimatedValue();
                updatePressureStatus();
                invalidate();
            });
            systolicAnimator.start();
        } else {
            systolicValue = value;
            updatePressureStatus();
            invalidate();
        }
    }

    // 设置舒张压（带动画）
    public void setDiastolicValue(int value, boolean animate) {
        if (value < DIA_MIN) value = DIA_MIN;
        if (value > DIA_MAX) value = DIA_MAX;

        if (diastolicAnimator != null && diastolicAnimator.isRunning()) {
            diastolicAnimator.cancel();
        }

        if (animate) {
            diastolicAnimator = ValueAnimator.ofInt(diastolicValue, value);
            diastolicAnimator.setDuration(1500);
            diastolicAnimator.addUpdateListener(animation -> {
                diastolicValue = (int) animation.getAnimatedValue();
                updatePressureStatus();
                invalidate();
            });
            diastolicAnimator.start();
        } else {
            diastolicValue = value;
            updatePressureStatus();
            invalidate();
        }
    }

    // 设置血压值（带动画）
    public void setBloodPressure(int systolic, int diastolic, boolean animate) {
        setSystolicValue(systolic, animate);
        setDiastolicValue(diastolic, animate);
    }

    // 获取当前收缩压值
    public int getSystolicValue() {
        return systolicValue;
    }

    // 获取当前舒张压值
    public int getDiastolicValue() {
        return diastolicValue;
    }

    // 获取血压状态
    public String getPressureStatus() {
        return pressureStatus;
    }
}